package com.bdk.middle.management.filter;

/**
 * @Author: xxx
 * @Date: 2021/3/3 0003 17:30
 * @Description:
 */
import com.bdk.middle.common.result.ResultDO;
import com.bdk.middle.management.api.domain.RoleDO;
import com.bdk.middle.management.jwt.JwtTokenUtil;
import com.bdk.middle.management.service.PermissionService;
import com.bdk.middle.management.service.RoleService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 登录成功后 走此类进行鉴权操作
 */
public class JWTAuthorizationFilter extends BasicAuthenticationFilter {

    private PermissionService permissionService;
    private RoleService roleService;

    public JWTAuthorizationFilter(AuthenticationManager authenticationManager, PermissionService permissionService,RoleService roleService) {

        super(authenticationManager);
        this.permissionService=permissionService;
        this.roleService=roleService;
    }

    /**
     * 在过滤之前和之后执行的事件
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain chain) throws IOException, ServletException {
        String tokenHeader = request.getHeader(JwtTokenUtil.TOKEN_HEADER);
        // 若请求头中没有Authorization信息 或是Authorization不以Bearer开头 则直接放行
        if (tokenHeader == null || !tokenHeader.startsWith(JwtTokenUtil.TOKEN_PREFIX)) {
            chain.doFilter(request, response);
            return;
        }

        // 若请求头中有token 则调用下面的方法进行解析 并设置认证信息
        SecurityContextHolder.getContext().setAuthentication(getAuthentication(tokenHeader));
        super.doFilterInternal(request, response, chain);
    }

    /**
     * 从token中获取用户信息并新建一个token
     *
     * @param tokenHeader 字符串形式的Token请求头
     * @return 带用户名和密码以及权限的Authentication
     */
//    private UsernamePasswordAuthenticationToken getAuthentication(String tokenHeader) {
//
//        // 去掉前缀 获取Token字符串
//        String token = tokenHeader.replace(JwtTokenUtil.TOKEN_PREFIX, "");
//        // 从Token中解密获取用户名
//        String username = JwtTokenUtil.getUsername(token);
//        // 从Token中解密获取用户角色
//        String roles = JwtTokenUtil.getUserRole(token);
//        Collection<RoleDO> authorities = new ArrayList<>();
//        if(!roles.equals("")) {
//            Gson gson = new Gson();
//            authorities = gson.fromJson(roles, new TypeToken<List<RoleDO>>(){}.getType());
//        }
//        if (username != null)
//        {
//            return new UsernamePasswordAuthenticationToken(username, null,authorities);
//        }
//        return null;
//    }

    /**
     * 从token中获取用户信息并新建一个token
     *
     * @param tokenHeader 字符串形式的Token请求头
     * @return 带用户名和密码以及权限的Authentication
     */
    private UsernamePasswordAuthenticationToken getAuthentication(String tokenHeader) {

        // 去掉前缀 获取Token字符串
        String token = tokenHeader.replace(JwtTokenUtil.TOKEN_PREFIX, "");
        // 从Token中解密获取用户名
        String username = JwtTokenUtil.getUsername(token);
        // 查用户权限字符串，然后组装传递给spring security
        Collection<GrantedAuthority> authorities = new HashSet<>();
        ResultDO result=permissionService.getPermissionByUsername(username);
        if(!result.isSuccess()) {
          return null;
        }
        Set<String> permissionSet=(Set<String>)result.getModel(ResultDO.FIRST_MODEL_KEY);

        for(String permissionStr:permissionSet){
            authorities.add(new SimpleGrantedAuthority(permissionStr));
        }
        //添加角色到spring security
        ResultDO result2=roleService.getRolesByUsername(username);
        if(!result2.isSuccess()) {
            return null;
        }
        Set<String> roleSet=(Set<String>)result2.getModel(ResultDO.FIRST_MODEL_KEY);
        for(String roleStr:roleSet){
            authorities.add(new SimpleGrantedAuthority("ROLE_"+roleStr));
        }

        if (username != null)
        {
            return new UsernamePasswordAuthenticationToken(username, null,authorities);
        }
        return null;
    }
}